package com.polaris.live.widget.task

import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.doOnLayout
import com.blankj.utilcode.util.ColorUtils
import com.polaris.live.R
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.WidgetTaskProgressBinding
import com.polaris.live.resp.back_resp.UserProgressReward

/**
 * TaskProgressView 主播任务带进度
 *
 * @author Created by 天晴 on 2024/1/24 19:17
 * @since 1.0.0
 **/
class TaskProgressView(context: Context, attributeSet: AttributeSet) :
    RelativeLayout(context, attributeSet) {

    private val mBinding = WidgetTaskProgressBinding.inflate(LayoutInflater.from(context), this)

    private var mWidth = 0

    private val maxWidth = 75.autoDp

    private var oneProgressWidth = maxWidth //一個進度的寬度

    private var lastRewards: List<UserProgressReward>? = null
    private var viewList: List<TaskViewsBean> = arrayListOf()

    private var clickBack: ((explainType: Long) -> Unit)? = null

    init {
        mBinding.root.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (ViewUtils.isContextValid(context)) {
                    mWidth = mBinding.root.width
                    lastRewards?.let {
                        setData(it)
                    }
                }

                mBinding.root.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    fun setItemListener(
        clickBack: ((explainType: Long) -> Unit)? = null,
    ) {
        this.clickBack = clickBack
    }

    private fun setDataView(rewards: List<UserProgressReward>) {
        rewards.forEachIndexed { index, da ->
            viewList.getOrNull(index)?.apply {
                mProgressBar?.max = da.total.toInt()
                mProgressBar?.progress = da.value.toInt()
                when (da.status) {
                    0L -> { //进行中
                        mImageView?.setImageResource(R.drawable.task_anchor_no)
                    }

                    1L, 2L -> { //可领取
                        mImageView?.setImageResource(R.drawable.task_anchor_ok)
                    }
                }
                if (!da.unit.isNullOrEmpty()) {
                    mTextView?.text = da.unit
                }
                mTaskNodeView?.setData(da)
            }
        }

    }

    fun setData(rewards: List<UserProgressReward>) {
        if (lastRewards != null && rewards[0].taskId == lastRewards!![0].taskId && viewList.size == rewards.size) {
            setDataView(rewards)
            return
        }

        this.lastRewards = rewards
        if (mWidth != 0 && rewards.isNotEmpty()) {
            mBinding.progressCl.removeAllViews()
            oneProgressWidth = if (rewards.size <= 4) {
                (mWidth - 40.autoDp) / rewards.size
            } else {
                maxWidth
            }
            var pId = ConstraintLayout.LayoutParams.PARENT_ID
            rewards.forEach { da ->
                val bean = TaskViewsBean()
                val progress = newProgressBar(pId)
                bean.mProgressBar = progress
                mBinding.progressCl.addView(progress)
                progress.doOnLayout {
                    progress.max = da.total.toInt()
                    progress.progress = da.value.toInt()
                }
                pId = progress.id
                addNodeView(progress, da, bean)
            }
        }
    }

    private fun addNodeView(
        view: View,
        item: UserProgressReward,
        bean: TaskViewsBean,
    ) {
        mBinding.scrollView.post {
            if (!this.isAttachedToWindow) return@post
            val imageView = ImageView(context)
            bean.mImageView = imageView
            imageView.id = View.generateViewId()
            val lp = ConstraintLayout.LayoutParams(15.autoDp, 15.autoDp)
            lp.topToTop = view.id
            lp.bottomToBottom = view.id
            lp.endToEnd = view.id
            lp.marginEnd = (-7).autoDp
            imageView.layoutParams = lp
            when (item.status) {
                0L -> { //进行中
                    imageView.setImageResource(R.drawable.task_anchor_no)
                }

                1L, 2L -> { //可领取
                    imageView.setImageResource(R.drawable.task_anchor_ok)
                }
            }
            mBinding.progressCl.addView(imageView)

            if (!item.unit.isNullOrEmpty()) {
                val textView = TextView(context)
                bean.mTextView = textView
                val textLp = ConstraintLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
                textLp.bottomToTop = imageView.id
                textLp.startToStart = imageView.id
                textLp.endToEnd = imageView.id
                textLp.bottomMargin = 4.autoDp
                textView.text = item.unit
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
                textView.setTextColor(ColorUtils.getColor(R.color.color_893AFF))
                textView.layoutParams = textLp
                mBinding.progressCl.addView(textView)
            }

            val node = TaskNodeView(context, null)
            bean.mTaskNodeView = node
            val nodeLp = ConstraintLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
            nodeLp.topToBottom = imageView.id
            nodeLp.startToStart = imageView.id
            nodeLp.endToEnd = imageView.id
            node.layoutParams = nodeLp
            mBinding.progressCl.addView(node)
            node.setData(item)
            node.setOnClickListener {
                clickBack?.invoke(item.rewardExplainType)
            }
        }

    }

    private fun newProgressBar(
        start: Int = ConstraintLayout.LayoutParams.PARENT_ID,
    ): ProgressBar {
        val progressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal).apply {
            id = View.generateViewId()
            layoutParams = ConstraintLayout.LayoutParams(
                oneProgressWidth,
                3.autoDp
            ).apply {
                topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                if (start == ConstraintLayout.LayoutParams.PARENT_ID) {
                    startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                } else {
                    startToEnd = start
                }
                topMargin = 30.autoDp
            }
            progressDrawable = ContextCompat.getDrawable(context, R.drawable.task_progress_bar2)?.mutate()
        }
        return progressBar
    }

}

data class TaskViewsBean(
    var mProgressBar: ProgressBar? = null,
    var mImageView: ImageView? = null,
    var mTextView: TextView? = null,
    var mTaskNodeView: TaskNodeView? = null,
)